﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IWshRuntimeLibrary;

namespace WeChatDouble
{
    public static class Common 
    {
        /// <summary>
        /// 读取注册表
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ReadRegistry(string keyName, string path)
        {
            try
            {
                RegistryKey hklm = Registry.CurrentUser;
                RegistryKey hkSoftWare = hklm.OpenSubKey(path, true);
                if (hkSoftWare != null && hkSoftWare.GetValue(keyName) != null)
                {
                    var str = hkSoftWare.GetValue(keyName).ToString();
                    hklm.Close();
                    hkSoftWare.Close();
                    return str;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取注册表异常");
                return null;
            }
        }

        /// <summary>
        /// 判断是否启动过
        /// </summary>
        /// <param name="ProcedureName"></param>
        /// <returns></returns>
        public static bool IsAfterStart(string ProcedureName)
        {
            try
            {
                if (System.Diagnostics.Process.GetProcessesByName(ProcedureName).ToList().Count > 0)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("程序启动检测失败！");
            }
            return true;
        }

        /// <summary>
        /// 关闭进程
        /// </summary>
        /// <param name="strProcessesByName"></param>
        public static void KillProcess(string strProcessesByName)
        {
            foreach (Process p in Process.GetProcesses())
            {
                if (p.ProcessName == strProcessesByName)
                {
                    try
                    {
                        p.Kill();
                        p.WaitForExit(); // possibly with a timeout
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("关闭失败，请手动关闭!", "提示");   // process was terminating or can't be terminated - deal with it
                    }
                }
            }
        }

        /// <summary>
        /// 判断指定文件是否存在
        /// </summary>
        /// <param name="PathStr">文件路径</param>
        /// <returns></returns>
        public static bool IsFileExist(string PathStr)
        {
            try
            {
                return System.IO.File.Exists(PathStr) ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="PathStr">文件路径</param>
        /// <param name="str">内容字符窜</param>
        public static void CreateFile(string PathStr, string str)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            try
            {
                StreamWriter sw = new StreamWriter(PathStr, false, Encoding.GetEncoding("gb2312"));
                sw.WriteLine(str);//开始写入值
                sw.Close();
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 创建快捷方式
        /// </summary>
        /// <param name="PathStr"></param>
        /// <param name="name"></param>
        public static void Createlnk(string PathStr,string name,string imangpath)
        {
            //实例化WshShell对象
            WshShell shell = new WshShell();
            //通过该对象的 CreateShortcut 方法来创建 IWshShortcut 接口的实例对象
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "//"+name);
            //设置快捷方式的目标所在的位置(源程序完整路径)
            shortcut.TargetPath = PathStr;
            //应用程序的工作目录
            //当用户没有指定一个具体的目录时，快捷方式的目标应用程序将使用该属性所指定的目录来装载或保存文件。
            shortcut.WorkingDirectory = System.Environment.CurrentDirectory;
            //目标应用程序窗口类型(1.Normal window普通窗口,3.Maximized最大化窗口,7.Minimized最小化)
            shortcut.WindowStyle = 1;
            //快捷方式的描述
            shortcut.Description = "微信多开";
            //可以自定义快捷方式图标.(如果不设置,则将默认源文件图标.)
            shortcut.IconLocation = imangpath;// System.Environment.SystemDirectory + "\\" + "shell32.dll, 165";
            
            //保存快捷方式
            shortcut.Save();
        }

        /// <summary>
        /// 创建 .lnk 快捷方式
        /// </summary>
        /// <param name="shortcutPath">快捷方式完整路径（含 .lnk）</param>
        /// <param name="targetPath">目标程序路径（.exe）</param>
        /// <param name="description">快捷方式描述</param>
        /// <param name="workingDirectory">启动目录（通常为 exe 所在目录）</param>
        public static void CreateShortcut(string shortcutPath, string targetPath, string description, string workingDirectory)
        {
            WshShell shell = new WshShell();
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);

            shortcut.TargetPath = targetPath;                 // 目标程序
            shortcut.WorkingDirectory = workingDirectory;     // 启动目录
            shortcut.Description = description;               // 描述
            shortcut.IconLocation = targetPath + ",0";        // 使用目标程序图标
                                                              // 可选：添加启动参数
                                                              // shortcut.Arguments = "--multi-instance";

            shortcut.Save();
        }

    }
}
